package com.pureut.storage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.storage.domain.*;
import com.pureut.storage.dto.IncomingMaterialPrintingDetailDto;
import com.pureut.storage.dto.IncomingMaterialSubcontractPrintingDto;
import com.pureut.storage.dto.WarehouseStringDto;
import com.pureut.storage.mapper.*;
import com.pureut.storage.service.*;
import com.pureut.storage.utils.DocumentTypeEnum;
import com.pureut.storage.vo.IncomingMaterialSubcontractPrintingVo;
import com.pureut.storage.vo.OneKeyWarehousingVo;
import com.sale.common.core.exception.GlobalException;
import com.sale.common.dict.utils.DictUtils;
import com.sale.common.satoken.utils.LoginHelper;
import com.sale.system.api.domain.SysDictData;
import com.sale.system.api.domain.vo.SysResultMaterialVo;
import com.sale.system.api.domain.vo.SysReturnStatusVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/***
 * 委外打印实现层
 * Author:C
 * Date:2022/12/28 11:16
 * @DESC
 */
@Service
public class IncomingMaterialSubcontractPrintingServiceImpl extends ServiceImpl<IncomingMaterialSubcontractPrintingMapper, IncomingMaterialSubcontractPrinting> implements IncomingMaterialSubcontractPrintingService {

    @Resource
    IncomingMaterialSubcontractPrintingMapper incomingMaterialSubcontractPrintingMapper;

    @Resource
    IncomingMaterialPrintingDetailMapper incomingMaterialPrintingDetailMapper;

    @Resource
    IncomingMaterialPrintingDetailService incomingMaterialPrintingDetailService;

    @Resource
    SubcontractReceiptService subcontractReportService;

    @Resource
    SubcontractReceiptDetailMapper subcontractReceiptDetailMapper;

    @Resource
    SubcontractReceiptDetailService subcontractReceiptDetailService;

    @Resource
    WmsStockInfoMapper wmsStockInfoMapper;

    @Resource
    WmsStockInfoService wmsStockInfoService;

    @Resource
    WarehouseService warehouseService;

    //物料mapper
    @Resource
    PublicMaterialMapper publicMaterialMapper;

//    @Resource
//    OrderFeignService orderFeignService;

    /**
     * 委外打印列表
     *
     * @param incomingMaterialSubcontractPrintingVo
     * @return
     */
    @Override
    public List<IncomingMaterialSubcontractPrintingDto> getSubcontractPrintList(IncomingMaterialSubcontractPrintingVo incomingMaterialSubcontractPrintingVo) {
        List<SysDictData> printArray = DictUtils.getDictCache("print_status");
        Map<String, String> printMap = printArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        List<IncomingMaterialSubcontractPrintingDto> subcontractPrintList = incomingMaterialSubcontractPrintingMapper.getSubcontractPrintList(incomingMaterialSubcontractPrintingVo);
        for (IncomingMaterialSubcontractPrintingDto entity : subcontractPrintList) {
            entity.setPrintStatusDict(printMap.get(String.valueOf(entity.getPrintStatus())));
            entity.setDocumentTypeDict(DocumentTypeEnum.getValue(Integer.parseInt(entity.getDocumentType())));
        }
        return subcontractPrintList;
    }

    /**
     * 委外打印详情
     *
     * @param id
     * @return
     */
    @Override
    public IncomingMaterialSubcontractPrintingDto getSubcontractPrintView(long id) {
        //获取网型标准缓存字典数据
        List<SysDictData> netArray = DictUtils.getDictCache("sys_of_type");
        Map<String, String> netMap = netArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        IncomingMaterialSubcontractPrintingDto subPrintView = incomingMaterialSubcontractPrintingMapper.getSubPrintView(id);
        //网型
        subPrintView.setMaterialNetDict(netMap.get(subPrintView.getMaterialNet()));
        //获取该数据下的明细
        List<IncomingMaterialPrintingDetail> incomingMaterialPrintingDetails = incomingMaterialPrintingDetailMapper.selectList(new QueryWrapper<IncomingMaterialPrintingDetail>().lambda().eq(IncomingMaterialPrintingDetail::getSubcontractId, id));
        BigDecimal totalWeight = new BigDecimal(0);

        for (IncomingMaterialPrintingDetail entity : incomingMaterialPrintingDetails) {
            totalWeight = totalWeight.add(new BigDecimal(String.valueOf(entity.getGrossWeight())));
        }

        //平均净重
        subPrintView.setAverageNetWeight(incomingMaterialPrintingDetails.get(0).getNetWeight());
        //本批净重
        subPrintView.setNetWeight(Double.parseDouble(totalWeight.toString()));
        //本批数量
        subPrintView.setQuantityBatch(subPrintView.getQuantityBatch());
        return subPrintView;
    }

    /**
     * 一键入库
     *
     * @param oneKeyWarehousingVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean oneKeyWarehousing(OneKeyWarehousingVo oneKeyWarehousingVo) {
        //通过库位编码获取仓库信息
        WarehouseStringDto warehouseCode = warehouseService.getWarehouseCode(oneKeyWarehousingVo.getKwCode());
        //获取委外打印信息
        IncomingMaterialSubcontractPrinting incomingMaterialSubcontractPrinting = getById(oneKeyWarehousingVo.getId());
        if (incomingMaterialSubcontractPrinting.getPrintStatus() == 3) {
            //获取委外打印明细信息
            List<IncomingMaterialPrintingDetailDto> list = incomingMaterialPrintingDetailService.getSubcontractList(oneKeyWarehousingVo.getId());

            //算出入库重量
            BigDecimal bigDecimal = new BigDecimal("0");


            //根据批次号查询委外入库明细
            List<SubcontractReceiptDetail> subcontractReceiptDetailList = subcontractReceiptDetailMapper.selectList(new QueryWrapper<SubcontractReceiptDetail>().lambda().eq(SubcontractReceiptDetail::getSubcontractId, list.get(0).getReceiptId()));
            for (SubcontractReceiptDetail entity : subcontractReceiptDetailList) {
                BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(entity.getNetWeight()));
                bigDecimal = bigDecimal.add(bigDecimal1);
                entity.setStatus(2);
                //仓库信息
                entity.setWarehouseMessage(warehouseCode.getCombinationName());
                //入库人
                entity.setWarehouseInBy(LoginHelper.getUsername());
                //入库时间
                entity.setWarehouseInTime(new Date());
            }
            //修改委外入库明细信息状态为已入库
            subcontractReceiptDetailMapper.updateBatchById(subcontractReceiptDetailList);

            //修改委外入库信息为已完成
            SubcontractReceipt byId = subcontractReportService.getById(subcontractReceiptDetailList.get(0).getSubcontractId());


            //入库重量
            byId.setWarehousingWeight(Double.parseDouble(bigDecimal.toString()));

            //入库数量
            byId.setWarehousingNum(subcontractReceiptDetailList.size());

            //查出物料单位
            PublicMaterial publicGoods = publicMaterialMapper.selectOne(new QueryWrapper<PublicMaterial>().lambda().eq(PublicMaterial::getMaterialCode, incomingMaterialSubcontractPrinting.getMaterialCode()));

            //实际量
            //判断单位是kg还是吨
            if ("2".equals(publicGoods.getMaterialUnit())) {
                byId.setActualQuantity(bigDecimal.toString());
            } else if ("3".equals(publicGoods.getMaterialUnit())) {
                BigDecimal bigDecimal1 = new BigDecimal("1000");

                BigDecimal divide = new BigDecimal(bigDecimal.toString()).divide(bigDecimal1);

                byId.setActualQuantity(divide.toString());
            } else {
                byId.setActualQuantity(subcontractReceiptDetailList.size() + "");
            }

            //判断该单据的委外打印单据是否都为已完成
            List<IncomingMaterialSubcontractPrinting> incomingMaterialSubcontractPrintings = incomingMaterialSubcontractPrintingMapper.selectList(new QueryWrapper<IncomingMaterialSubcontractPrinting>().lambda().eq(IncomingMaterialSubcontractPrinting::getReceiptNo, byId.getReceiptNo()));
            boolean isAll = true;
            for (IncomingMaterialSubcontractPrinting entity : incomingMaterialSubcontractPrintings) {
                if (entity.getPrintStatus() != 4) {
                    isAll = false;
                }
            }
            //如果对应的单据信息都为已完成，且计划量大于等于实际量，就修改委外入库单为已完成
            boolean b;
            double plannedWeight = byId.getPlannedWeight();
            b = Double.parseDouble(byId.getActualQuantity()) >= plannedWeight;
            if (isAll && b) {
                byId.setStatus(4);
            } else {
                byId.setStatus(2);
            }
            subcontractReportService.updateById(byId);

            //获取仓库数据
            List<WmsStockInfo> wmsStockInfoList = wmsStockInfoMapper.selectList(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialBatch, subcontractReceiptDetailList.get(0).getBatchNo()));
            for (WmsStockInfo entity : wmsStockInfoList) {
                entity.setWsiMaterialStatus(2);

                entity.setWsiWarehourse(String.valueOf(warehouseCode.getCkId()));
                entity.setWsiReservoirArea(String.valueOf(warehouseCode.getKqId()));
                entity.setWsiStorageLoaction(String.valueOf(warehouseCode.getKwId()));
                entity.setWsiWarehourseInfo(warehouseCode.getCombinationName());
                entity.setWsiMaterialGrade("1");
                entity.setWsiConnectNum(byId.getSubcontractOrderNo());//关联单号
                entity.setWsiDocNum(byId.getReceiptNo());//仓库关联单号
            }
            //修改仓库数据
            wmsStockInfoMapper.updateBatchById(wmsStockInfoList);
            incomingMaterialSubcontractPrinting.setPrintStatus(4);

//            // 数据回传至委外订单
//            UpdateSubcontractingOrderDataVo updateSubcontractingOrderDataVo = new UpdateSubcontractingOrderDataVo();
//            updateSubcontractingOrderDataVo.setSubcontractingOrderNumber(byId.getSubcontractOrderNo());
//            updateSubcontractingOrderDataVo.setArriveWeight(Double.parseDouble(bigDecimal.toString()));
//            updateSubcontractingOrderDataVo.setStatus(byId.getStatus());
//            orderFeignService.updateSubcontractingOrderData(updateSubcontractingOrderDataVo);

            return updateById(incomingMaterialSubcontractPrinting);
        } else {
            throw new GlobalException("只能操作待入库的数据");
        }
    }

    /**
     * 根据唯一标识修改状态(feign调用)
     *
     * @param sysReturnStatusVo
     * @return
     */
    @Override
    public boolean getDataByOnlyMarkSub(SysReturnStatusVo sysReturnStatusVo) {
        IncomingMaterialSubcontractPrinting incomingMaterialSubcontractPrinting = incomingMaterialSubcontractPrintingMapper.selectOne(new QueryWrapper<IncomingMaterialSubcontractPrinting>().lambda().eq(IncomingMaterialSubcontractPrinting::getOnlyMark, sysReturnStatusVo.getOnlyMark()));

        incomingMaterialSubcontractPrinting.setPrintStatus(2);
        List<SysResultMaterialVo> materialList = sysReturnStatusVo.getMaterialList();
        String averageTare = materialList.get(0).getAverageTare();

        //根据id获取明细数据
        List<IncomingMaterialPrintingDetail> incomingMaterialPrintingDetails = incomingMaterialPrintingDetailMapper.selectList(new QueryWrapper<IncomingMaterialPrintingDetail>().lambda().eq(IncomingMaterialPrintingDetail::getSubcontractId, incomingMaterialSubcontractPrinting.getId()));
        for (IncomingMaterialPrintingDetail entity : incomingMaterialPrintingDetails) {
//            //毛重 - 皮重
//            int round = (int) Math.round(entity.getGrossWeight());
//            int integer = Integer.parseInt(averageTare);
//            BigDecimal subtract = new BigDecimal(String.valueOf(round)).subtract(new BigDecimal(integer));
//            String s = subtract.toString();
            entity.setNetWeight(entity.getGrossWeight());
        }
        incomingMaterialPrintingDetailService.batchUpdate(incomingMaterialPrintingDetails);
        return updateById(incomingMaterialSubcontractPrinting);
    }
}
